package com.mas.framework.security.core.service;

import com.mas.admin.api.permission.PermissionApi;
import com.mas.framework.security.core.pojo.LoginUser;
import lombok.AllArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;


/**
 * @author godyao
 * @description 默认的 {@link SecurityFrameworkService} 实现类
 * @date 2023年01月28日13:31
 */
@AllArgsConstructor
public class SecurityFrameworkServiceImpl implements SecurityFrameworkService{

    private final PermissionApi permissionApi;

    @Override
    public boolean hasPermission(String permission) {
        return hasAnyPermissions(permission);
    }

    @Override
    public boolean hasAnyPermissions(String... permissions) {
        return permissionApi.hasAnyPermissions(getLoginUserId(), permissions);
    }

    /**
     * 获得当前用户的编号，从上下文中
     * @return 用户编号
     */
    @Nullable
    public static Long getLoginUserId() {
        Optional<LoginUser> loginUser = getLoginUser();
        return loginUser.map(LoginUser::getId).orElse(null);
    }

    /**
     * 获取当前用户
     * @return 当前用户
     */
    public static Optional<LoginUser> getLoginUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return Optional.empty();
        }
        if (authentication.getPrincipal() instanceof LoginUser) {
            return Optional.ofNullable((LoginUser) authentication.getPrincipal());
        }
        return Optional.empty();
    }

    /**
     * 获得当前认证信息
     *
     * @return 认证信息
     */
    public static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return null;
        }
        return context.getAuthentication();
    }

    @Override
    public boolean hasRole(String role) {
        return hasAnyRoles(role);
    }

    @Override
    public boolean hasAnyRoles(String... roles) {
        return permissionApi.hasAnyRoles(1L, roles);
    }

    @Override
    public boolean hasScope(String scope) {
        return hasAnyScopes(scope);
    }

    @Override
    public boolean hasAnyScopes(String... scope) {
        // TODO
        return false;
        //LoginUser user = SecurityFrameworkUtils.getLoginUser();
        //if (user == null) {
        //    return false;
        //}
        //return CollUtil.containsAny(user.getScopes(), Arrays.asList(scope));
    }
}
